package com.leyou.page.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.page.service.PageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/10 0010
 * Time: 22:14
 */
@Slf4j
@Service
public class PageServiceImpl implements PageService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private SpringTemplateEngine templateEngine;
    @Value("${ly.static.itemDir}")
    private String itemDir;
    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    @Override
    public Map<String, Object> loadGoodsById(Long id) {
        //查询spu
        SpuDTO spuDTO = itemClient.querySpuById(id);
        //查询规格组
        List<SpecGroupDTO> specs = itemClient.querySpecsByCid3(spuDTO.getCid3());
        //查询品牌
        BrandDTO brandDTO = itemClient.queryBrandById(spuDTO.getBrandId());
        //查询分类集合
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spuDTO.getCategoryIds());

        // 封装数据
        Map<String, Object> data = new HashMap<>(10);
        data.put("categories", categories);
        data.put("brand", brandDTO);
        data.put("spuName", spuDTO.getName());
        data.put("subTitle", spuDTO.getSubTitle());
        data.put("skus", spuDTO.getSkus());
        data.put("detail", spuDTO.getSpuDetail());
        data.put("specs", specs);
        return data;
    }

    public void createItemHtml(Long id) {
        // 1 上下文准备模板数据
        Context context = new Context();
        // 2 调用加载数据的方法
        context.setVariables(loadGoodsById(id));
        // 3 写出的文件的路径
        File dir = new File(itemDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                // 3.1 创建失败
                log.error("【静态页面服务】 创建静态页面目录失败，目录地址:{}", dir.getAbsolutePath());
                throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
            }
        }
        File filePath = new File(dir, id + ".html");
        // 4 准备输出流
        try (PrintWriter writer = new PrintWriter(filePath, "utf-8")) {
            templateEngine.process(itemTemplate, context, writer);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【静态页面服务】 静态页面生成失败，商品id:{}", id, e);
        }
    }

    @Override
    public void insertHtmlBySpuId(Long spuId) {
        createItemHtml(spuId);
        System.out.println("新增静态页面");

    }

    @Override
    public void deleteHtmlBySpuId(Long spuId) {
        File file = new File("item", spuId + ".html");
        if (file.exists()) {
            if (!file.delete()) {
                log.error("【静态页面服务】 删除静态页面失败，商品id:{}", spuId);
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
        }
    }
}
